package com.ldk.admin.controller;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.SESSION;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.ICjtCityService;
import com.ldk.framework.service.ICjtRoadService;
import com.ldk.framework.service.ICompanypermitService;

import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

@Controller
@RequestMapping("/citroad")
public class CjtRoadController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "citroad";
    /**
     * 模块名称
     */
    private final String module = "城际通路线";

    @Autowired
    private ICjtCityService cjtCityService;

    @Autowired
    private ICjtRoadService cjtRoadService;

    @Autowired
    private ICompanypermitService companypermitService;


    @RequestMapping("/list")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
        } else {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        }

        map.addAttribute("route", route);
        map.addAttribute("companyList", getCompanyList());
        //操作日志
        //this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
		/*if (this.getRoleId(request) == 6) {
			return new ModelAndView("/cjt/listdict_sj");
		} else {
			return new ModelAndView("/cjt/listdict");
		}*/
        return new ModelAndView("/cjt/roadlist");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<CjtRoad> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                              @RequestParam(value = "startCity", required = false, defaultValue = "") String startCity,
                                              @RequestParam(value = "endCity", required = false, defaultValue = "") String endCity,
                                              @RequestParam(value = "companyId", required = false, defaultValue = "") String companyId,
                                              @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                              HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        CjtRoad query = new CjtRoad();
        if (!TextUtils.isEmpty(startCity)) {
            query.setStartCity(startCity);
        }
        if (!TextUtils.isEmpty(endCity)) {
            query.setEndCity(endCity);
        }
        if (!TextUtils.isEmpty(companyId)) {
            query.setCompanyId(companyId);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<CjtRoad> result = cjtRoadService.selectPageList("", query, pageable);

        LigerUIGridResult<CjtRoad> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();
        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);

        map.addAttribute("companyList", getCompanyList());
        map.addAttribute("cityList", getCityList());

        CjtRoad model = new CjtRoad();

        return new ModelAndView("/cjt/roadinfo", "model", model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        CjtRoad query = new CjtRoad();
        query.setId(id);

        CjtRoad model = cjtRoadService.selectByKey("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + id, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("companyList", getCompanyList());
        map.addAttribute("cityList", getCityList());

        return new ModelAndView("/cjt/roadinfo", "model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") CjtRoad model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        if (TextUtils.isEmpty(model.getStartCity()) || TextUtils.isEmpty(model.getEndCity())) {
            rst.AddError(String.format("出发城市，到达城市不能为空"));
            return new ModelAndView("redirect:/" + route + "/add");
        }
        try {
            String fromTo = model.getStartCity() + "--" + model.getEndCity();
            model.setFromTo(fromTo);
            CjtRoad query = new CjtRoad();
            query.setFromTo(fromTo);

            CjtRoad exitObject = cjtRoadService.selectOne("", query);
            if (exitObject != null) {
                rst.AddError(String.format("%s已经存在", model.getFromTo()));
                return new ModelAndView("redirect:/" + route + "/add");
            }
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            model.setKmPrice(ConvertUtil.toFiexd(model.getMileage() / model.getPrice()));
            if(model.getChargeRatio()==null){
                model.setChargeRatio(0.0);
            }
            if(model.getSubChargeRatio()==null){
                model.setSubChargeRatio(0.0);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());

            this.insertOplog(request, module, "", "", "添加:" + model.getFromTo(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = cjtRoadService.insert("", model);
            if (row > 0) {
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败，失败原因：" + e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") CjtRoad model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        AdminUser admin = (AdminUser)request.getSession().getAttribute(SESSION.USER);
        if(admin == null){
            return new ModelAndView("redirect:/login");
        }
        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            CjtRoad query = new CjtRoad();
            query.setFromTo(model.getFromTo());

            CjtRoad exitObject = cjtRoadService.selectOne("", query);
            if (exitObject != null && exitObject.getId() != model.getId()) {
                rst.AddError(String.format("%s已经存在", model.getFromTo()));
                return new ModelAndView("redirect:/" + route + "/edit/{id}");
            }

            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if(model.getChargeRatio()==null){
                model.setChargeRatio(0.0);
            }
            if(model.getSubChargeRatio()==null){
                model.setSubChargeRatio(0.0);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());
            model.setOperate(admin.getUserName());
            this.insertOplog(request, module, "", "", "添加:" + model.getFromTo(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = cjtRoadService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败，失败原因：" + e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setViewMode(map, ViewMode.View);
        CjtRoad query = new CjtRoad();
        query.setId(id);
        CjtRoad model = cjtRoadService.selectByKey("", query);
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("companyList", getCompanyList());
        map.addAttribute("cityList", getCityList());

        return new ModelAndView("/cjt/roadinfo", "model", model);
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        int row = 0;
        try {
            //操作日志
            CjtRoad query = new CjtRoad();
            query.setId(id);
            CjtRoad dict = cjtRoadService.selectByKey("", query);
            this.insertOplog(request, module, "", "", "删除:" + dict.getFromTo(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            row = cjtRoadService.deleteByKey("", query);
        } catch (Exception e) {

        }
        if (row > 0) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }


    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }

    /**
     * 获取开通城市列表
     *
     * @return
     */
    private List<CjtCity> getCityList() {
        CjtCity query = new CjtCity();
        query.setEnabled(true);

        return cjtCityService.selectList("", query);
    }
}
